package com.mzkj.wanjulaile.mobile.api.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.mzkj.common.data.StatusCode;
import com.mzkj.common.utils.SpringContextHolder;
import com.mzkj.common.utils.StringUtils;
import com.mzkj.wanjulaile.mobile.api.common.entity.ResultEntity;
import com.mzkj.wanjulaile.mobile.api.modules.session.entity.Session;
import com.mzkj.wanjulaile.mobile.api.modules.session.service.SessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * token认证拦截器
 * Created by wangxw on 2016/12/12.
 */
public class AuthInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    @Transactional
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(">>>AuthInterceptor---start>>>>>>>");
        String accessToken = request.getParameter("accessToken");
        String refreshToken = request.getHeader("X-ToyStory-Refresh-Token");
        ResultEntity resultEntity;
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        SessionService sessionService = (SessionService) factory.getBean("sessionService");
        if (StringUtils.isEmpty(accessToken)) {
            resultEntity = new ResultEntity(StatusCode.SC2004);
        } else {
            resultEntity = sessionService.validAccessToken(accessToken);
        }
//        if (!StatusCode.SC0.getValue().equals(resultEntity.getStatusCode())) {
//            String resultJson = JSON.toJSONString(resultEntity);
//            PrintWriter writer = null;
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("text/html; charset=utf-8");
//            try {
//                writer = response.getWriter();
//                writer.print(resultJson);
//            } catch (IOException e) {
//                logger.error(e.getMessage(), e);
//            } finally {
//                if (writer != null)
//                    writer.close();
//            }
//            return false;
//        } else {
//            Session session = sessionService.findByAccessToken(accessToken);
//            request.setAttribute("accountId", session.getAccountId());
//            return true;
//        }
        if (StatusCode.SC0.getValue().equals(resultEntity.getStatusCode()) ||
                (StatusCode.SC2001.getValue().equals(resultEntity.getStatusCode()) && StringUtils.isNotEmpty(refreshToken))) {
            if (StatusCode.SC2001.getValue().equals(resultEntity.getStatusCode())) {
                request.setAttribute("valid_access_token_rs", "2001");
            }
            Session session = sessionService.findByAccessToken2(accessToken);
            if (session != null) {
                request.setAttribute("accountId", session.getAccountId());
            }
            return true;
        } else {
            String resultJson = JSON.toJSONString(resultEntity);
            PrintWriter writer = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            try {
                writer = response.getWriter();
                writer.print(resultJson);
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (writer != null)
                    writer.close();
            }
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(">>>AuthInterceptor---end>>>>>>>");
    }
}
